<template>
  <view class="content">
    <view class="tips">{{ this.allObj ? this.allObj.storeName : "" }}</view>
    <view class="xh-box">{{ this.allObj ? this.allObj.storeNumber : "" }}</view>
    <view class="swiper-area">
      <swiper
        class="swiper-box"
        :current="current"
        indicatorDots
        @change="SwiperChange"
        :disableTouch="current === 0"
      >
        <swiper-item>
          <div class="canvas-container" ref="canvasRef"></div>
        </swiper-item>
        <swiper-item v-if="gsImgUrl">
          <image :src="gsImgUrl" style="width: 100%; height: 100%"></image>
        </swiper-item>
        <swiper-item v-if="bdImgUrl"
          ><image :src="bdImgUrl" style="width: 100%; height: 100%"></image
        ></swiper-item>
        <swiper-item v-if="jhImgUrl"
          ><image :src="jhImgUrl" style="width: 100%; height: 100%"></image
        ></swiper-item>
      </swiper>
      <view
        v-if="current === 0 && (gsImgUrl || bdImgUrl || jhImgUrl)"
        class="left-icon"
        @click="leftEvent"
      >
        <u-icon name="arrow-left-double"></u-icon>
      </view>
      <view
        v-if="current === 0 && (gsImgUrl || bdImgUrl || jhImgUrl)"
        class="right-icon"
        @click="rightEvent"
      >
        <u-icon name="arrow-right-double"></u-icon>
      </view>
    </view>
    <view class="scroll-area">
      <!-- <view v-for="(item, index) in initArr" :key="index">
        <selectArea :object="item" @selectColor="selectColor"></selectArea>
      </view> -->
      <!-- 镜框色 -->
      <selectArea :object="jkObj" @selectColor="selectColor"></selectArea>
      <!-- 镜腿色 -->
      <selectArea :object="jtObj" @selectColor="selectColor"></selectArea>
      <!-- 镜片色 -->
      <jpSelectArea :object="jpObj" @selectColor="selectColor"></jpSelectArea>
      <!-- 挂绳配置 -->
      <selectArea :object="gsObj" @selectColor="selectColor"></selectArea>
      <!-- 布袋配置 -->
      <selectArea :object="bdObj" @selectColor="selectColor"></selectArea>
      <!-- 眼镜盒配置 -->
      <selectArea :object="jhObj" @selectColor="selectColor"></selectArea>
      <view>
        <!-- <selectLogo
          :object="logoObj"
          @selectColor="selectColor"
          @selectBtn="selectBtn"
        ></selectLogo> -->
      </view>
      <view>
        <glassesLogo
          :object="glassesObj"
          @inputChange="inputChange"
          :ztList="ztList"
          @ztChange="ztChange"
          @selectBtn="selectBtn"
          :explain="logoExplain"
        ></glassesLogo>
      </view>
    </view>
    <u-gap height="170rpx" bgColor="#fff"></u-gap>
    <view class="bottom-area">
      <!-- <view class="left-btn btn-item" @click="selectModel">选择定制型号</view> -->
      <view class="left-btn">
        <view class="price-area">
          <span>支付金额：¥</span>
          <span style="margin-left: 10rpx">{{
            submitObj.glassesBagPrice + submitObj.glassesCasePrice + submitObj.sportHangPrice
          }}</span>
        </view>
        <view class="sure-btn" @click="selectModel">确认</view>
      </view>
      <view class="right-btn btn-item" @click="sureEvent">试戴</view>
    </view>
    <view class="loading-box" v-if="loading">
      <u-loading-icon
        :text="loadText"
        textSize="30"
        textColor="#fff"
        color="#fff"
        :show="loading"
      ></u-loading-icon>
    </view>
  </view>
</template>

<script>
import * as THREE from "three";
import glasses from "@/mixins/3dGless.js";
import selectArea from "./components/selectArea.vue";
import jpSelectArea from "./components/jpSelectArea.vue";
import selectLogo from "./components/selectLogo.vue";
import glassesLogo from "./components/glassesLogo.vue";
import { generateImageLink } from "./js/createImg.js";
import { createGradientMaterial } from "./js/jbs.js";
import wx from "weixin-js-sdk";
export default {
  mixins: [glasses],
  components: { selectArea, selectLogo, glassesLogo, jpSelectArea },
  data() {
    return {
      initArr: [],
      glassesObj: {
        id: "glassesLogo",
        title: "镜片Logo定制",
      },
      currentLogoMesh: null,
      jkObj: {}, //镜框OBj
      jtObj: {}, //镜腿OBj
      jpObj: {}, //镜片OBj
      gsObj: {}, //挂绳OBj
      bdObj: {}, //布袋OBj
      jhObj: {}, //眼镜盒OBj
      bdImgUrl: "",
      gsImgUrl: "",
      jhImgUrl: "",
      ztList: [],
      logoExplain: "",
      isInit: false,
      loading: true,
      loadText: "加载中",
      priceTotal: 0,
      submitObj: {
        logoText: {
          fontFamily: "",
          value: "",
        },
        logoImg: {
          value: "",
        },
        glassesFrame: {
          name: "",
          value: "",
        }, // 眼镜腿
        glassesLeg: {
          name: "",
          value: "",
        }, // 眼镜片
        lensObj: {
          name: "",
          value: [],
        }, // 运动绳
        sportHang: {
          name: "",
          value: "",
          price: "",
          pic: "",
        }, // 眼镜袋
        glassesBag: {
          name: "",
          pic: "",
          price: "",
        }, // 眼镜盒
        glassesCase: {
          name: "",
          value: "",
          price: "",
          pic: "",
        },
        totalPrice: "",
        id: "",
        glassesBagPrice: 0,
        glassesCasePrice: 0,
        sportHangPrice: 0,
      },
    };
  },
  onLoad() {
    const id = this.$route.query.tenantId;
    console.log("id", id);
  },
  mounted() {
    uni.$on("logoPic", async (url) => {
      if (this.currentLogoMesh) {
        this.scene.remove(this.currentLogoMesh);
      }
      this.submitObj.logoImg.value = url;
      const logoTexture = await this.createLogoTexture(url, true);
      // 创建一个新的平面几何体来放置LOGO
      const logoGeometry = new THREE.PlaneGeometry(1, 1);
      const logoMaterial = new THREE.MeshBasicMaterial({
        map: logoTexture,
        transparent: true,
        side: THREE.FrontSide,
      });
      this.currentLogoMesh = new THREE.Mesh(logoGeometry, logoMaterial);
      this.currentLogoMesh.renderOrder = 2;
      // 将LOGO平面放置在原始镜片LOGO的位置
      this.currentLogoMesh.position.set(0, 0.54, 0.018);
      // 将LOGO添加到场景中
      this.scene.add(this.currentLogoMesh);
    });
  },
  methods: {
    // #B56CBF,#462626,#564BBC
    selectColor(info) {
      console.log("info", info);

      if (info.id === "glassesFrame") {
        this.submitObj.glassesFrame = {
          name: info.color.name,
          value: info.color.value,
        };
        this.current = 0;
        this.modelTwo.material.color.set(info.color.value);
        this.initFx();
        // 重置模型的位置和旋转
        if (this.currentLogoMesh) {
          this.currentLogoMesh.rotation.y = 0;
          this.currentLogoMesh.position.set(0, 0.54, 0.018);
        }
      }
      if (info.id === "glassesLeg") {
        this.submitObj.glassesLeg = {
          name: info.color.name,
          value: info.color.value,
        };
        this.current = 0;
        this.modelFour.material.color.set(info.color.value);
        this.initFx();
        this.modelAll.rotateY(Math.PI / 2);
        this.modelAll.position.set(0.2, 0.4, 0);
        if (this.currentLogoMesh) {
          this.currentLogoMesh.rotation.y = Math.PI / 2;
          this.currentLogoMesh.position.set(0.218, 0.535, 0);
        }
      }
      if (info.id === "lensColor") {
        this.submitObj.lensObj = {
          name: info.color.name,
          value: info.color.assistColors,
        };
        this.current = 0;
        this.initFx();
        if (info.color.assistColors && info.color.assistColors.length) {
          const gradientMaterial = createGradientMaterial(
            info.color.assistColors
          );
          this.modelOne.material = gradientMaterial;
        } else {
          this.glassMaterial = new THREE.MeshPhysicalMaterial({
            color: "#00000", // 假设使用绿色，运动风格的颜色
            roughness: 0.3, // 增加粗糙度以减少透明度效果，但保持一定的透明感
            metalness: 0.1, // 增加金属度以增加反光效果
            transparent: true, // 启用透明度
            opacity: 0.8, // 设置透明度值，比原来的要高一些，以体现半透明效果
            envMapIntensity: 0.8, // 减少环境贴图强度，以控制反光效果
            transmission: 0.7, // 减少折射度，以减少光线衰减程度
            clearcoat: 0.1, // 增加清漆效果
            clearcoatRoughness: 0.1,
            refractionRatio: 1.3, // 减少折射率，以控制光的折射程度
          });
          this.modelOne.material = this.glassMaterial;
          this.modelOne.material.color.set(info.color.mainColor);
        }
        if (this.currentLogoMesh) {
          this.currentLogoMesh.rotation.y = 0;
          this.currentLogoMesh.position.set(0, 0.54, 0.018);
        }
      }
      if (info.id === "sportHang") {
        this.submitObj.sportHang = {
          name: info.color.name,
          value: info.color.value,
          price: info.color.price,
          pic: info.color.pic,
        };
        if (!info.color) {
          this.current = 0;
          this.gsImgUrl = "";
          this.submitObj.sportHangPrice = 0;
        } else {
          this.current = 1;
          this.gsImgUrl = info.color.pic;
          this.submitObj.sportHangPrice = Number(this.allObj.sportHangPrice);
        }
      }
      if (info.id === "glassesBag") {
        this.submitObj.glassesBag = {
          name: info.color.name,
          value: info.color.value,
          price: info.color.price,
          pic: info.color.pic,
        };
        if (!info.color) {
          this.current = 0;
          this.bdImgUrl = "";
          this.submitObj.glassesBagPrice = 0;
        } else {
          this.current = 2;
          this.bdImgUrl = info.color.pic;
          this.submitObj.glassesBagPrice = Number(this.allObj.glassesBagPrice);
        }
      }
      if (info.id === "glassesCase") {
        this.submitObj.glassesCase = {
          name: info.color.name,
          value: info.color.value,
          price: info.color.price,
          pic: info.color.pic,
        };
        if (!info.color) {
          this.current = 0;
          this.jhImgUrl = "";
          this.submitObj.glassesCasePrice = 0;
        } else {
          this.current = 3;
          this.jhImgUrl = info.color.pic;
          this.submitObj.glassesCasePrice = Number(this.allObj.glassesCasePrice);
        }
      }
    },
    ztChange(info) {
      this.submitObj.logoText.fontFamily = info.value;
    },
    selectBtn(info) {
      if (info.id === "wz") {
        this.submitObj.logoImg = null;
        if (this.currentLogoMesh) {
          this.scene.remove(this.currentLogoMesh);
        }
        this.submitObj.logoImg = null;
      } else {
        this.submitObj.logoText.value = "";
        if (this.currentLogoMesh) {
          this.scene.remove(this.currentLogoMesh);
        }
      }
    },
    async inputChange(val) {
      this.current = 0;
      if (this.currentLogoMesh) {
        this.scene.remove(this.currentLogoMesh);
      }
      if (!this.isInit) {
        this.initFx();
        this.isInit = true;
      }
      if (val) {
        this.submitObj.logoText.value = val;
        const logoTexture = await this.createLogoTexture(val, false);
        // 创建一个新的平面几何体来放置LOGO
        const logoGeometry = new THREE.PlaneGeometry(1, 1);
        const logoMaterial = new THREE.MeshBasicMaterial({
          map: logoTexture,
          transparent: true,
          side: THREE.FrontSide,
        });
        this.currentLogoMesh = new THREE.Mesh(logoGeometry, logoMaterial);
        this.currentLogoMesh.renderOrder = 2;
        // 将LOGO平面放置在原始镜片LOGO的位置
        // this.currentLogoMesh.position.y=40;
        this.currentLogoMesh.position.set(0, 0.54, 0.018);
        // 将LOGO添加到场景中
        // 动态定位逻辑
        // this.currentLogoMesh.scale.setScalar(cameraDistance * 0.03);
        this.scene.add(this.currentLogoMesh);
      }
    },
    sureEvent() {
      generateImageLink(this.modelAll).then((res) => {
        uni.setStorageSync("img", res);
        uni.navigateTo({
          url: `/pages/home/wearingGlasses`,
        });
      });
    },
    selectModel() {
      this.submitObj.totalPrice =
        this.submitObj.glassesBagPrice + this.submitObj.glassesCasePrice + this.submitObj.sportHangPrice;
      generateImageLink(this.modelAll).then((res) => {
        this.submitObj.picture = res;
        wx.miniProgram.postMessage({
          data: {
            action: "submit",
            formData: {
              /* 你的表单数据 */
              submitObj: this.submitObj,
            },
          },
        });
        // 可选：通知小程序环境销毁时接收消息（如页面跳转前）
        // wx.miniProgram.navigateBack('/pages/customized/customizedGlasses/fourth/index');
        wx.miniProgram.navigateBack({
          url: `/pages/homePage/mainIndex&tenantId=6`,
        });
        console.log("this.submitObj", this.submitObj);
      });
    },
    initFx() {
      // 完整重置逻辑
      this.modelAll.position.copy(this.initialModelState.position);
      this.modelAll.rotation.copy(this.initialModelState.rotation);
      this.modelAll.scale.copy(this.initialModelState.scale);

      // 重置控制器状态
      this.controls.target.set(0, 0.5, 0); // 与初始化时保持一致
      this.controls.reset();

      // 重置相机位置
      this.camera.position.set(0, 0.5, 1.6);
      this.camera.lookAt(0, 0.5, 0);

      // 强制更新矩阵
      this.modelAll.updateMatrixWorld(true);
    },
  },
};
</script>

<style lang="scss" scoped>
.canvas-container {
  width: 100%;
  height: 450rpx;
  position: relative;
}
::v-deep  .swiper-box {
  height: 450rpx !important;
}
.swiper-area {
  position: relative;
  .left-icon {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.1);
    padding: 10rpx;
    border-radius: 10rpx;
  }
  .right-icon {
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.1);
    padding: 10rpx;
    border-radius: 10rpx;
  }
}
.content {
  height: 100vh;
  width: 100vw;
  display: flex;
  position: relative;
  flex-direction: column;
  .scroll-area {
    flex: 1;
    overflow: auto;
  }
  .tips {
    font-size: 24rpx;
    color: #999999;
    line-height: 32rpx;
    text-align: center;
    padding: 20rpx 0;
  }
  .xh-box {
    font-size: 44rpx;
    color: #000000;
    line-height: 56rpx;
    text-align: center;
  }
}
.bottom-area {
  position: fixed;
  bottom: 0;
  width: 100vw;
  background-color: #000;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  .btn-item {
    background-color: #fff;
    color: #000;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 600;
    padding: 20rpx;
    border-radius: 60rpx;
  }
  padding-bottom: calc(
    20rpx + constant(safe-area-inset-bottom)
  ); ///兼容 IOS<11.2/
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
  .left-btn {
    width: 60%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .sure-btn {
      background-color: #fff;
      color: #000;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: 600;
      padding: 20rpx 60rpx;
      border-radius: 60rpx;
    }
    .price-area {
      color: #fff;
      font-size: 28rpx;
    }
  }
  .right-btn {
    width: 28%;
  }
}
.loading-box {
  width: 100%;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
